<template>
  <el-dialog v-model="dialogVisible" title="商品分类信息" destroy-on-close width="60%">
    <el-form :model="form" label-width="80px" style="padding: 20px 30px 10px 0">
      <el-form-item prop="fenlei" label="分类名称">
        <el-input v-model="form.fenlei" autocomplete="off" placeholder="请输入分类名称"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="save">
          保存
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { defineProps, defineEmits, ref, watch } from 'vue'
import request from "@/utils/request";

const props = defineProps({
  modelValue: {
    type: Boolean,
    required: true
  },
  form: {
    type: Object,
    required: true
  }
})

const emit = defineEmits(['update:modelValue', 'save'])

// 本地维护一份 form，避免直接修改 props
const dialogVisible = ref(false)
const form = ref({})

// 同步 props.form 到本地 form
watch(() => props.form, (newVal) => {
  form.value = { ...newVal }
}, { deep: true, immediate: true })

// 同步 modelValue 到 dialogVisible
watch(() => props.modelValue, (val) => {
  dialogVisible.value = val
})

// 当 dialogVisible 改变时更新 modelValue
watch(dialogVisible, (val) => {
  emit('update:modelValue', val)
})

const save = () => {
  if (form.value.id) {
    // 修改
    request.put('/shangpinfenlei/update', form.value).then(res => {
      if (res.code === '200') {
        ElMessage.success('更新成功')
        emit('save')
        dialogVisible.value = false
      } else {
        ElMessage.error(res.msg)
      }
    })
  } else {
    // 新增
    request.post('/shangpinfenlei/add', form.value).then(res => {
      if (res.code === '200') {
        ElMessage.success('新增成功')
        emit('save')
        dialogVisible.value = false
      } else {
        ElMessage.error(res.msg)
      }
    })
  }
}
</script>
